import WebSocket, { WebSocketServer } from 'ws';
import express from 'express';
import http from 'http';
import cors from 'cors';

const app = express();

app.use(cors());

const server = http.createServer(app);

const wss = new WebSocketServer({
    server,
    perMessageDeflate: {
        zlibDeflateOptions: {
            chunkSize: 1024,
            memLevel: 7,
            level: 3
        },
        zlibInflateOptions: {
            chunkSize: 10 * 1024
        },
        clientNoContextTakeover: true,
        serverNoContextTakeover: true,
        serverMaxWindowBits: 10,
        concurrencyLimit: 10,
        threshold: 1024
    }
});

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        console.log(message);
        console.log(`Received message => ${message}`);
        if (message) {
            ws.send(`返回信息：${message.toString()}`);
        }
    });
});

// 通过 WebSocket 的协议打开服务器
server.listen(8080, () => {
    console.log('Server started on port 8080');
});
